
#import "ChooseEffectViewController.h"
#import "FindLampResultViewController.h"
#import "lampmeta.h"
#import "CustomNavigationBar.h"
#import "UINavigationItem+Customization.h"
#import "HelpViewController.h"
#import "Data.h"
#import "InformationCell.h"
#import "NSString+VoiceOver.h"

#define kInactivityTimeout 3
#define kFilamentFileExtension @"-trad"
#define kGlowFileExtension @"-glod"

@interface ChooseEffectViewController () <UITableViewDataSource, UITableViewDelegate, InformationCellDelegate>

@end

@implementation ChooseEffectViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.png"]];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
            
    UIButton *infoButton = [[UIButton alloc] initWithFrame:CGRectZero];
    [infoButton setImage:[UIImage imageNamed:@"btn-info-off.png"] forState:UIControlStateNormal];
    [infoButton setImage:[UIImage imageNamed:@"btn-info-on.png"] forState:UIControlStateHighlighted];
    [infoButton setImage:[UIImage imageNamed:@"btn-info-on.png"] forState:UIControlStateSelected];
    [infoButton sizeToFit];
    [infoButton addTarget:self action:@selector(showInfo) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *infoBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:infoButton];
    infoBarButtonItem.accessibilityLabel = @"Hjälp";
    self.navigationItem.rightBarButtonItems = @[infoBarButtonItem];

    UIImage *slideMin = [[UIImage imageNamed:@"slide-bg-fill.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
    UIImage *slideMax = [[UIImage imageNamed:@"slide-bg.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
    
    [self.slider setMinimumTrackImage:slideMin forState:UIControlStateNormal];
    [self.slider setMaximumTrackImage:slideMax forState:UIControlStateNormal];
    [self.slider setThumbImage:[UIImage imageNamed:@"slide-pitch.png"] forState:UIControlStateNormal];
    [self.slider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    [self.slider addTarget:self action:@selector(sliderTouchUp:) forControlEvents:UIControlEventTouchUpInside];
    [self.slider addTarget:self action:@selector(sliderTouchUp:) forControlEvents:UIControlEventTouchUpOutside];
    
    self.slider.transform = CGAffineTransformMakeRotation(M_PI * -0.5);
    
    self.overlayView.delegate = self;
    self.navigationItem.title = _(@"Välj effekt");
    [self.navigationItem customizeTitleInNavigationBarWithHeight:self.navigationController.navigationBar.frame.size.height];
    
    if (voiceoverEnabled) {
        self.accessibilityTableView.hidden = NO;
        UIImageView *bgImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg"]];
        [bgImageView setFrame:self.accessibilityTableView.bounds];
        self.accessibilityTableView.backgroundView = bgImageView;
        self.accessibilityTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.accessibilityTableView setContentInset:UIEdgeInsetsMake(22,0,22,0)];
    }    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    CustomNavigationBar* customNavigationBar = (CustomNavigationBar*)self.navigationController.navigationBar;
    [customNavigationBar applyDefaultStyle];
    
    UIButton* backButton = [customNavigationBar backButtonWith:[UIImage imageNamed:@"btn-back-off.png"] highlight:[UIImage imageNamed:@"btn-back-on.png"] leftCapWidth:14.0 title:_(@"Välj lampa")];
    backButton.titleLabel.textColor = [UIColor whiteColor];
    backButton.titleLabel.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:12];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self startInactivityTimer];
}

- (void)viewDidUnload
{
    [self setSlider:nil];
    [self setEffectLabel:nil];
    [self setLumenLabel:nil];
    [self setOverlayView:nil];
    [self setFilamentView:nil];
    [self setLightOnView:nil];
    [self setLampView:nil];
    [self setAccessibilityTableView:nil];
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)setLampItem:(NSDictionary *)lampItem
{
    _lampItem = lampItem;
    
    float effectValue = [self loadSavedEffectValue];
   
    if (!effectValue) {
        effectValue = [self.lampItem[kLampItemEffects][0] integerValue];
    }
    self.slider.minimumValue = 0;
    self.slider.maximumValue = [[self.lampItem[kLampItemEffects] lastObject] integerValue];
    self.slider.value = effectValue;
    
    [self updateEffectAndLumenLabels];
    [self initLampView];
    [self updateLampViews];
}

- (void)initLampView
{
    NSString *lampFileName = [self.lampItem valueForKey:kLampItemImage];
    self.lampView.image = [UIImage imageNamed:lampFileName];
    self.filamentView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@%@", lampFileName, kFilamentFileExtension]];
    self.lightOnView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@%@", lampFileName, kGlowFileExtension]];
}

#pragma mark - 
- (float)loadSavedEffectValue
{
    return [[NSUserDefaults standardUserDefaults] floatForKey:[self.lampItem valueForKey:kLampItemCaption]];
}

- (void)saveEffectValue:(float)value
{
    [[NSUserDefaults standardUserDefaults] setFloat:self.slider.value forKey:[self.lampItem valueForKey:kLampItemCaption]];
}

#pragma mark - Selectors

- (void)continueButtonPressed:(id)sender 
{
    FindLampResultViewController *resultVC = [[FindLampResultViewController alloc] initWithNibName:@"FindLampResultViewController" bundle:nil];
    [self.navigationController pushViewController:resultVC animated:YES];
}

- (void)sliderValueChanged:(id)sender
{
    [self hideOverlayView];

    [self updateEffectAndLumenLabels];
    
    [self updateLampViews];
}

- (void)updateEffectAndLumenLabels
{
    NSInteger effect = [self.lampItem[kLampItemEffects][[self effectIndexForSliderValue:self.slider.value]] integerValue];
    self.effectLabel.text = [NSString stringWithFormat:_(@"Effekt %d watt"), effect];
    self.lumenLabel.text = [NSString stringWithFormat:_(@"motsvarar %@ lumen (lm)"),
                            [[Data sharedInstance] lumenStringFromWattValue:effect lampType:self.lampItem[kLampItemType]]];
}

- (void)updateLampViews
{
    self.filamentView.alpha = [self filamentAlphaForValue:(self.slider.value/self.slider.maximumValue)];
    self.lightOnView.alpha = [self lightningboltAlphaForValue:(self.slider.value/self.slider.maximumValue)];  
}

- (void)sliderTouchUp:(id)sender
{
    [self.slider setValue:[self.lampItem[kLampItemEffects][[self effectIndexForSliderValue:self.slider.value]] integerValue] animated:YES];
    [self animateToAlpha:[self filamentAlphaForValue:(self.slider.value/self.slider.maximumValue)] onView:self.filamentView];
    [self animateToAlpha:[self lightningboltAlphaForValue:(self.slider.value/self.slider.maximumValue)] onView:self.lightOnView];
    [self saveEffectValue:self.slider.value];
}

- (void)animateToAlpha:(CGFloat)alpha onView:(UIView *)view
{
    [UIView animateWithDuration:0.25 animations:^{
        view.alpha = alpha;
    }];
}

- (CGFloat)filamentAlphaForValue:(CGFloat)value
{
    return pow(value, 0.3);
}

- (CGFloat)lightningboltAlphaForValue:(CGFloat)value
{
    return 1.1 * pow((1-cos(value * M_PI))/2, .4);
}

- (void)userSwipedRight:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSInteger)effectIndexForSliderValue:(CGFloat)value
{
    NSArray *effects = self.lampItem[kLampItemEffects];
    
    NSInteger minIndex = 0;
    NSInteger minValue = 10000;
    
    for (NSInteger i = 0; i < effects.count; i++) {
        NSNumber *effect = effects[i];
        NSInteger currentEffect = self.slider.value;
        NSInteger delta = ABS([effect integerValue] - currentEffect);
        if (delta < minValue) {
            minValue = delta;
            minIndex = i;
        } else {
            break;
        }
    }
    return minIndex;
}

- (void)showChooseEffectOverlayView
{
    self.overlayView.userInteractionEnabled = YES;
    [UIView animateWithDuration:0.25 animations:^{
        self.overlayView.alpha = 1.0;
    } completion:^(BOOL finished) {
    }];
}

- (void)startInactivityTimer
{
    [inactivityTimer invalidate];
    inactivityTimer = [NSTimer scheduledTimerWithTimeInterval:kInactivityTimeout target:self selector:@selector(showChooseEffectOverlayView) userInfo:nil repeats:NO];
}

- (void)stopInactivityTimer
{
    [inactivityTimer invalidate];
    inactivityTimer = nil;
}

- (void)showInfo
{
    HelpViewController *helpVC = [[HelpViewController alloc] initWithNibName:nil bundle:nil];
    helpVC.documentFile = _(@"Power");
    helpVC.title = _(@"Hjälp");
    [self presentModalViewController:helpVC animated:YES];
}

- (void)hideOverlayView
{
    self.overlayView.userInteractionEnabled = NO;
    [UIView animateWithDuration:0.25 animations:^{
        self.overlayView.alpha = 0;
    } completion:^(BOOL finished) {
        [self startInactivityTimer];
    }];
}

#pragma mark - Touches
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self hideOverlayView];
}

-(void)goToResultView
{
    FindLampResultViewController *resultVC = [[FindLampResultViewController alloc] initWithNibName:@"FindLampResultViewController" bundle:nil];
    resultVC.savingsCalculator = [[SavingsCalculator alloc] initWithLampItem:self.lampItem effect:self.slider.value];
    [self.navigationController pushViewController:resultVC animated:YES];
}

#pragma mark - ChooseEffectOverlayViewDelegate methods
- (void)toResultButtonPressed
{
    [self stopInactivityTimer];
    self.overlayView.userInteractionEnabled = NO;
    self.overlayView.alpha = 0;

    [self goToResultView];
}

- (void)chooseEffectOverlayTouched
{
    [self goToResultView];
}

#pragma mark - EffectLampImageView delegate methods
- (void)userTappedOnLamp
{
    [self stopInactivityTimer];
    self.overlayView.userInteractionEnabled = NO;
    self.overlayView.alpha = 0;

    [self goToResultView];
}

#pragma mark - Table view datasource
#define kNibName @"InformationCell"
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [(self.lampItem)[kLampItemEffects] count];
}

static CGFloat cellHeight = 0; // Static because height does not change
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!cellHeight) {
        UITableViewCell *cell = [[NSBundle mainBundle] loadNibNamed:kNibName owner:self options:nil][0];
        cellHeight = cell.frame.size.height;
    }
    return cellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    InformationCell *cell = (InformationCell *)[tableView dequeueReusableCellWithIdentifier:kNibName];
    if (!cell) {
        cell = [[NSBundle mainBundle] loadNibNamed:kNibName owner:self options:nil][0];
        cell.delegate = self;
    }
	cell.tag = indexPath.row;
    NSInteger effect = [(self.lampItem)[kLampItemEffects][indexPath.row] integerValue];
    
//    LampType lampType = [[Data sharedInstance] lampTypeFromString:self.lampItem[kLampItemType]];
    NSString *interval = [[Data sharedInstance] lumenStringFromWattValue:effect lampType:self.lampItem[kLampItemType]];
    cell.titleLabel.text = [NSString stringWithFormat:@"%d W motsvarar %@ lm", effect, interval];
//    interval = [interval stringByReplacingOccurrencesOfString:@"–" withString:@"till"];
//    cell.titleLabel.accessibilityLabel = [NSString stringWithFormat:@"Effekten %d watt motsvarar %@ lumen", effect, interval];
    cell.titleLabel.accessibilityLabel = [cell.titleLabel.text stringByOptimizingForVoiceOver];
	return cell;
}

-(void)informationCellPressedWithTag:(NSInteger)tag
{
    FindLampResultViewController *resultVC = [[FindLampResultViewController alloc] initWithNibName:@"FindLampResultViewController" bundle:nil];
    resultVC.savingsCalculator = [[SavingsCalculator alloc] initWithLampItem:self.lampItem effect:[(self.lampItem)[kLampItemEffects][tag] integerValue]];
    [self.navigationController pushViewController:resultVC animated:YES];
}

@end
